<?php

namespace App\Repositories\Eloquent\Lst;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;

class StudentRepository extends Repository
{

    protected $user, $term;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Lst\Student';
    }


    public function confirm($request)
    {
        $detail = \App\Models\Lst\Detail::findOrFail($request->did);
        $user = \App\Models\Mgt\User::findOrFail($request->uid);

        $duplicate = \App\Models\Lst\Student::wherePublish($detail->publish_id)
                ->whereClase($detail->clase_id)
                ->where('uid', $user->id)
                ->first();
        if(!!$duplicate)
            return $this->responseFail(500,'重复加入班级花名册');

        $limited = \App\Models\Lst\Student::wherePublish($detail->publish_id)
                ->where('uid', $user->id)
                ->get();
        if($limited->count() >= $detail->publish->limit)
            return $this->responseFail(500,'加入班级花名册名额受限');

        \DB::beginTransaction();
        try{
            $student = $this->create([
                'publish_id'      => $detail->publish_id,
                'term_id'   => $detail->publish->term->id,
                'category_id'     => $detail->category_id,
                'clase_id'     => $detail->clase_id,
                'branch_id'     => $detail->category->branch_id,
                'uid'     => $user->id,
                'account'     => $user->account
            ]);

            \DB::commit();

            return $this->responseSuccess('加入班级花名册成功', $student, route('wx.settle.index'));

        } catch (Exception $e) {

            \DB::rollback();

            return $this->responseFail(500,'加入班级花名册失败');
        }
    }


    public function lists($request,$pid,$cid)
    {
        return $this->model->wherePublish($pid)->whereClase($cid)->get();
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $student = $this->find($id);

        if (!$student) {
            return $this->responseFail(404);
        }

        return $student;
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


}